package com.bd.wechat.service;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.bd.wechat.entity.response.map.MapR;
import com.bd.wechat.entity.response.map.MatrixResult;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.util.List;

@Data
@Service
public class TencentMapService implements Serializable {
    private static final String GEOCODE_URL = "https://apis.map.qq.com/ws/geocoder/v1/?address=%s&key=%s";
    private static final String MATRIX_URL = "https://apis.map.qq.com/ws/distance/v1/matrix?key=%s&from=%s&to=%s&mode=walking";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private String tencentMapApiKey;


    public String getGeocode(String address) {
        String url = String.format(GEOCODE_URL, address, tencentMapApiKey);
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        if (response.getStatusCode().is2xxSuccessful()) {
            return response.getBody();
        } else {
            throw new RuntimeException("Failed to get geocode from Tencent Map API");
        }
    }

    public String getMATRIX(String from, String to) {
        String url = String.format(MATRIX_URL, tencentMapApiKey, from, to);
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        if (response.getStatusCode().is2xxSuccessful()) {

            MapR<MatrixResult> mapR = JSONObject.parseObject(response.getBody(), new TypeReference<MapR<MatrixResult>>() {
            });

            return mapR.getResult().getRows().get(0).getElements().get(0).getDistance();
        } else {
            throw new RuntimeException("Failed to get geocode from Tencent Map API");
        }
    }


}
